<template>
  <div class="chart-container">
    <div ref="chartRef" class="chart" v-loading="loading"></div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import * as echarts from 'echarts'
import { useModulesStore } from '@/stores/modules'
import { getCurrentTheme, getTextColor, watchThemeChange, cleanupThemeWatch } from '@/utils/theme'

const modulesStore = useModulesStore()
const chartRef = ref(null)
const loading = ref(true)
let chartInstance = null
let themeWatchers = null

// 计算图表数据
const chartData = computed(() => {
  const dashboard = modulesStore.dashboardData

  // 如果有真实的dashboard数据，使用它
  if (dashboard && dashboard.topSizeModules && dashboard.topSizeModules.length > 0) {
    return dashboard.topSizeModules.map(module => ({
      name: module.name,
      size: module.size || 0 // 后台API返回的size已经是MB为单位
    }))
  }

  // 如果没有真实数据，使用模拟数据
  const modules = modulesStore.modules
  if (modules.length === 0) {
    return [
      { name: 'Foundation', size: 8.5 },
      { name: 'UIKit', size: 12.3 },
      { name: 'CoreFoundation', size: 6.8 },
      { name: 'libSystem', size: 4.2 },
      { name: 'AppKit', size: 15.7 },
      { name: 'CoreGraphics', size: 5.9 },
      { name: 'Metal', size: 3.4 },
      { name: 'AVFoundation', size: 7.1 },
      { name: 'CoreData', size: 2.8 },
      { name: 'Network', size: 3.1 }
    ]
  }

  return modules
    .sort((a, b) => (b.size || 0) - (a.size || 0))
    .slice(0, 10)
    .map(module => ({
      name: module.name,
      size: (module.size || 0) / (1024 * 1024) // 转换为MB
    }))
})

// 获取排序后的模块数据，用于图表显示
const sortedModulesData = computed(() => {
  return chartData.value
})

// 根据主题获取图表配置
const getChartOption = () => {
  const currentTheme = getCurrentTheme()
  const textColor = getTextColor(currentTheme)
  const sortedModules = sortedModulesData.value

  return {
    title: {
      text: 'TOP 10 模块大小分布',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: textColor
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: (params) => {
        const data = params[0]
        if (!data) return '未知模块'

        // 获取模块索引和名称
        const moduleIndex = data.dataIndex
        const moduleName = sortedModules[moduleIndex]?.name || '未知'
        const moduleSize = sortedModules[moduleIndex]?.size || 0

        return `${moduleName}<br/>大小: ${moduleSize.toFixed(2)} MB`
      },
      textStyle: {
        color: '#000000',
        fontWeight: 'bold'
      },
      backgroundColor: 'rgba(255, 255, 255, 0.95)',
      borderColor: '#333333',
      borderWidth: 1
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '大小 (MB)',
      nameTextStyle: {
        color: textColor,
        fontWeight: 'bold'
      },
      axisLabel: {
        formatter: '{value}',
        color: textColor,
        fontWeight: 'bold'
      },
      axisLine: {
        lineStyle: {
          color: textColor
        }
      }
    },
    yAxis: {
      type: 'category',
      data: sortedModules.map(item => item.name),
      axisLabel: {
        interval: 0,
        color: textColor,
        fontWeight: 'bold',
        formatter: (value) => {
          if (value.length > 15) {
            return value.substring(0, 12) + '...'
          }
          return value
        }
      },
      axisLine: {
        lineStyle: {
          color: textColor
        }
      }
    },
    series: [
      {
        name: '模块大小',
        type: 'bar',
        data: sortedModules.map(item => item.size),
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
            { offset: 0, color: '#83bff6' },
            { offset: 0.5, color: '#188df0' },
            { offset: 1, color: '#188df0' }
          ])
        }
      }
    ]
  }
}

const initChart = () => {
  if (!chartRef.value) return

  // 检查容器尺寸
  const container = chartRef.value
  if (container.clientWidth === 0 || container.clientHeight === 0) {
    // 如果容器尺寸为0，等待下一帧再试
    requestAnimationFrame(() => {
      setTimeout(() => initChart(), 100)
    })
    return
  }

  chartInstance = echarts.init(chartRef.value)
  chartInstance.setOption(getChartOption())

  // 设置主题变化监听
  themeWatchers = watchThemeChange(() => {
    if (chartInstance) {
      chartInstance.setOption(getChartOption())
    }
  })

  // 添加resize事件监听器，使用防抖
  let resizeTimer = null
  const resizeHandler = () => {
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
    resizeTimer = setTimeout(() => {
      if (chartInstance) {
        chartInstance.resize()
      }
    }, 200)
  }

  window.addEventListener('resize', resizeHandler)

  // 保存清理函数
  chartInstance.cleanup = () => {
    window.removeEventListener('resize', resizeHandler)
    if (resizeTimer) {
      clearTimeout(resizeTimer)
    }
  }
}

// 监听数据变化
watch(chartData, () => {
  if (chartInstance) {
    chartInstance.setOption(getChartOption())
  }
}, { deep: true })

onMounted(() => {
  setTimeout(() => {
    loading.value = false
    initChart()
  }, 500)
})

// 组件卸载时清理
onUnmounted(() => {
  if (themeWatchers) {
    cleanupThemeWatch(themeWatchers)
  }
  if (chartInstance) {
    if (chartInstance.cleanup) {
      chartInstance.cleanup()
    }
    chartInstance.dispose()
    chartInstance = null
  }
})
</script>

<style scoped lang="scss">
.chart-container {
  width: 100%;
  height: 100%;
  min-height: 300px;

  .chart {
    width: 100%;
    height: 100%;
    min-height: 300px;
  }
}
</style>